package com.cj.core.common;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CaptchaUtil {
    private static final String CHARACTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    private static final int WIDTH = 120; // 图片宽度
    private static final int HEIGHT = 40; // 图片高度
    private static final int CODE_LENGTH = 4; // 验证码长度
    private static final int LINE_COUNT = 8; // 干扰线数量

    /**
     * 生成随机验证码字符串
     *
     * @return 随机验证码字符串
     */
    public static String generateCode() {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        return code.toString();
    }

    /**
     * 根据验证码生成图片
     *
     * @param code 验证码字符串
     * @return 验证码图片
     */
    public static BufferedImage generateImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        // 填充背景
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置字体
        graphics.setFont(new Font("Arial", Font.BOLD, 28));

        // 绘制干扰线
        Random random = new Random();
        for (int i = 0; i < LINE_COUNT; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            graphics.drawLine(x1, y1, x2, y2);
        }

        // 绘制验证码字符
        for (int i = 0; i < CODE_LENGTH; i++) {
            graphics.setColor(new Color(random.nextInt(150), random.nextInt(150), random.nextInt(150)));
            graphics.drawString(String.valueOf(code.charAt(i)), 20 * i + 10, 30);
        }

        graphics.dispose();
        return image;
    }
}

